package com.lottery.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.lottery.common.util.Constant;
import com.lottery.web.model.Account;
import com.lottery.web.model.LotteryBettingInfo;
import com.lottery.web.model.LotteryBettingInfoListModel;
import com.lottery.web.service.LotteryBettingService;

/**
 * 
 * @author apple
 *
 */
@Controller
@RequestMapping("/lottery")
public class LotteryBettingController extends BaseController {

	private static Logger logger = Logger.getLogger(LotteryBettingController.class);

	@Resource
	private LotteryBettingService lotteryBettingService;
	

	@RequestMapping("/saveLotteryBttingRecord")
	@ResponseBody
	public String saveLotteryBttingRecord(@RequestBody LotteryBettingInfoListModel bettingInfoListModel,HttpSession session) {
		String userCode = (String) session.getAttribute(Constant.USERCODE);
//		userCode = "AG_1_P2";
		if (StringUtils.isBlank(userCode)) {
			return super.errorResult("userCode is blank,please login.");
		}
		if (logger.isDebugEnabled())
			logger.debug("saveLotteryBttingRecord start with bettingInfoList:"
					+ bettingInfoListModel);
		// 总消费
		double totalAmount = 0.0d;
		// 校验参数
		List<LotteryBettingInfo> bettingInfoList = bettingInfoListModel
				.getLotteryList();
		for (LotteryBettingInfo lottery : bettingInfoList) {
			// 设置投注人
			lottery.setLotteryUserCode(userCode);
			String validateStr = this.validateData(lottery);
			// 校验失败，流程结束
			if (StringUtils.isNotBlank(validateStr))
				return super.errorResult(validateStr + ",lotteryBettingCode:"
						+ lottery.getLotteryBettingCode());
			// 处理投注号码组集并计算总金额
			totalAmount += this.processBettingCodeList(lottery);
		}
		Map<String, Object> saveRetMap = null;
		try {
			saveRetMap = lotteryBettingService.saveLotteryBettingRecord(bettingInfoList, totalAmount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (saveRetMap == null) {
			return super.errorResult("投注失败");
		} else {
			boolean saveFlag = (Boolean) saveRetMap.get(Constant.RESULT_FLAG);
			if (saveFlag) {
				return super.jsonResult(null);
			} else {
				return super.errorResult("投注失败");
			}
		}
	}

	@RequestMapping("/cancelOrder")
	@ResponseBody
	public String cancelOrder(LotteryBettingInfo bettingInfo,HttpSession session) {
		String userCode = (String) session.getAttribute(Constant.USERCODE);
		if (StringUtils.isBlank(userCode)) {
			return super.errorResult("userCode is blank,please login.");
		}
		if (null == bettingInfo.getLotteryId()) {
			return super.errorResult("lottery_id is null.");

		}
		// 查当前用户是否与下单用户一致，并且订单是未开奖状态
		List<LotteryBettingInfo> bettingInfoList = lotteryBettingService.queryBettingInfo(bettingInfo);
		if (bettingInfoList != null && !bettingInfoList.isEmpty()) {
			LotteryBettingInfo queryInfo = bettingInfoList.get(0);
			if (null == queryInfo) {
				return super.errorResult("投注记录不存在或投注用户和记录不匹配");
			}
		}
		// 修改状态并修改用户余额
		Map<String, Object> cancelOrderRes = null;
		try {
			cancelOrderRes = lotteryBettingService.cancelOrder(bettingInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (cancelOrderRes != null && (Boolean) cancelOrderRes.get(Constant.RESULT_FLAG)) {
			return super.jsonResult(null);
		}
		return super.errorResult("撤单失败");
	}

	@RequestMapping("/queryLotteryDetail")
	@ResponseBody
	public String queryLotteryDetail(@RequestBody Map<String, Object> params, HttpSession session) {
		logger.info("begin queryLotteryDetail, params: " + params);
		Map<String, Object> retMap = new HashMap<String, Object>();
		Account userInfo = (Account) session.getAttribute(Constant.USER);
		String userCode = (String) session.getAttribute(Constant.USERCODE);
		if (StringUtils.isBlank(userCode)) {
			return super.errorResult("会话超时");
		}
		LotteryBettingInfo bettingInfo = new LotteryBettingInfo();
		if (null != params) {
			try {
				bettingInfo.setLotteryBettingMode((String) params.get("lotteryBettingMode"));
				bettingInfo.setLotteryBettingStatus((String) params.get("lotteryBettingStatus"));
				bettingInfo.setLotteryId((Integer) params.get("lotteryId"));
				bettingInfo.setLotteryType((String) params.get("lotteryType"));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				bettingInfo.setCreatedDate(sdf.parse((String) params.get("createdDate")));
				bettingInfo.setUpdatedDate(sdf.parse((String) params.get("updatedDate")));
			} catch (ParseException e) {
				logger.error("queryLotteryDetail exception: " + e.getMessage());
			} 
		}
		bettingInfo.setLotteryUserCode(userCode); 
		bettingInfo.setRole(userInfo.getRole());
		List<LotteryBettingInfo> lotteryBettingInfoList = lotteryBettingService
				.queryBettingInfo(bettingInfo);
		retMap.put("lotteryBettingInfoList", lotteryBettingInfoList);
		if (logger.isDebugEnabled())
			logger.debug("queryLotteryDetail end with retMap:" + retMap);
		return super.jsonResult(retMap);
	}
	
	@RequestMapping("/queryLastestLotteryDetail")
	@ResponseBody
	public String queryLastestLotteryDetail(HttpSession session) {
		logger.info("begin queryLastestLotteryDetail...");
//		String userCode = (String) session.getAttribute(Constant.USERCODE);
		Account userInfo = (Account) session.getAttribute(Constant.USER);
		String userCode = userInfo.getUserCode();
		if (StringUtils.isBlank(userCode)) {
			return super.errorResult("userCode is blank,please login.");
		}
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userCode", userCode);
		paramMap.put("role", userInfo.getRole());
//		LotteryBettingInfo lotteryBettingInfo = new LotteryBettingInfo();
//		lotteryBettingInfo.setLotteryUserCode(userCode);
//		lotteryBettingInfo.setLotteryUserRole();
		
		try {
			List<LotteryBettingInfo> lotteryBettingInfoList = this.lotteryBettingService.queryLastestBetteryInfo(paramMap);
			retMap.put("lotteryBettingInfoList", lotteryBettingInfoList);
			logger.info("queryLastestLotteryDetail result: " + retMap);
		} catch (Exception e) {
			logger.error("queryLastestLotteryDetail exception: " + e.getMessage());
		}
		
		return super.jsonResult(retMap);
	}

	private String validateData(LotteryBettingInfo bettingInfo) {
		if (StringUtils.isBlank(bettingInfo.getLotteryPeriods())) {// 开奖期数
			return super.errorResult("开奖期数为空，投注失败");
		}
		if (StringUtils.isBlank(bettingInfo.getLotteryType())) {// 彩票种类
			return super.errorResult("彩票种类为空，投注失败");
		}
		if (StringUtils.isBlank(bettingInfo.getLotteryPlay())) {// 彩票玩法
			return super.errorResult("彩票玩法为空，投注失败");
		}
		if (StringUtils.isBlank(bettingInfo.getLotteryBettingCode())) {// 投注号码
			return super.errorResult("投注号码为空，投注失败");
		}
		if (null == bettingInfo.getLotteryBettingNumber()) {// 投注数量
			return super.errorResult("投注数量为空，投注失败");
		}
		if (null == bettingInfo.getLotteryBettingMultiple()) {// 投注倍数
			return super.errorResult("投注倍数为空，投注失败");
		}
		if (null == bettingInfo.getLotteryBettingAmount()) {// 投注金额
			return super.errorResult("投注金额为空，投注失败");
		}

		if (StringUtils.isBlank(bettingInfo.getLotteryBettingMode())) {// 投注模式（单位）
			return super.errorResult("投注模式（单位）为空，投注失败");
		}
		if (null == bettingInfo.getLotteryBettingPrize()) {// 投注奖金
			return super.errorResult("投注奖金为空，投注失败");
		}
		return null;
	}

	public double processBettingCodeList(LotteryBettingInfo bettingInfo) {
		String bettingCode = bettingInfo.getLotteryBettingCode();
		String lotteryPlay = bettingInfo.getLotteryPlay();
		JSONArray bettingCodeList = new JSONArray();
		if (lotteryPlay.endsWith("单式") && bettingCode.contains("|")) {
			String[] bettingNumber = bettingCode.split("\\|");
			for (int h = 0; h < bettingNumber.length; h++) {
				if (lotteryPlay.startsWith("前三")) {// 前三单／复式
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								JSONArray codes = new JSONArray();
								codes.add(one[i]);
								codes.add(two[j]);
								codes.add(three[k]);
								codes.add("-");
								codes.add("-");
								bettingCodeList.add(codes);
							}
						}
					}
				} else if (lotteryPlay.startsWith("中三")) {// 中三单／复式
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								JSONArray codes = new JSONArray();
								codes.add("-");
								codes.add(one[i]);
								codes.add(two[j]);
								codes.add(three[k]);
								codes.add("-");
								bettingCodeList.add(codes);
							}
						}
					}
				} else if (lotteryPlay.startsWith("后三")) {// 后三单／复式
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								JSONArray codes = new JSONArray();
								codes.add("-");
								codes.add("-");
								codes.add(one[i]);
								codes.add(two[j]);
								codes.add(three[k]);
								bettingCodeList.add(codes);
							}
						}
					}
				} else if (lotteryPlay.startsWith("前四")) {// 前四单／复式
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					String[] four = bettingCodeArray[3].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								for (int l = 0; l < four.length; l++) {
									JSONArray codes = new JSONArray();
									codes.add(one[i]);
									codes.add(two[j]);
									codes.add(three[k]);
									codes.add(four[l]);
									codes.add("-");
									bettingCodeList.add(codes);
								}
							}
						}
					}
				} else if (lotteryPlay.startsWith("后四")) {// 后四单／复式
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					String[] four = bettingCodeArray[3].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								for (int l = 0; l < four.length; l++) {
									JSONArray codes = new JSONArray();
									codes.add("-");
									codes.add(one[i]);
									codes.add(two[j]);
									codes.add(three[k]);
									codes.add(four[l]);
									bettingCodeList.add(codes);
								}
							}
						}
					}
				} else if (lotteryPlay.startsWith("五星")) {
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					String[] four = bettingCodeArray[3].split(" ");
					String[] five = bettingCodeArray[4].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								for (int l = 0; l < four.length; l++) {
									for (int m = 0; m < five.length; m++) {
										JSONArray codes = new JSONArray();
										codes.add(one[i]);
										codes.add(two[j]);
										codes.add(three[k]);
										codes.add(four[l]);
										codes.add(five[m]);
										bettingCodeList.add(codes);
									}
								}
							}
						}
					}
				} else if (lotteryPlay.startsWith("前二")) {
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							JSONArray codes = new JSONArray();
							codes.add(one[i]);
							codes.add(two[j]);
							codes.add("-");
							codes.add("-");
							codes.add("-");
							bettingCodeList.add(codes);
						}
					}
				} else if (lotteryPlay.startsWith("后二")) {
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							JSONArray codes = new JSONArray();
							codes.add("-");
							codes.add("-");
							codes.add("-");
							codes.add(one[i]);
							codes.add(two[j]);
							bettingCodeList.add(codes);
						}
					}
				} else if (lotteryPlay.startsWith("任")) {
					String[] bettingCodeArray = bettingNumber[h].split(",");
					String[] one = bettingCodeArray[0].split(" ");
					String[] two = bettingCodeArray[1].split(" ");
					String[] three = bettingCodeArray[2].split(" ");
					String[] four = bettingCodeArray[3].split(" ");
					String[] five = bettingCodeArray[4].split(" ");
					for (int i = 0; i < one.length; i++) {
						for (int j = 0; j < two.length; j++) {
							for (int k = 0; k < three.length; k++) {
								for (int l = 0; l < four.length; l++) {
									for (int m = 0; m < five.length; m++) {
										JSONArray codes = new JSONArray();
										codes.add(one[i]);
										codes.add(two[j]);
										codes.add(three[k]);
										codes.add(four[l]);
										codes.add(five[m]);
										bettingCodeList.add(codes);
									}
								}
							}
						}
					}
				}
			}
		} else {
			if (lotteryPlay.startsWith("前三")) {// 前三单／复式
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							JSONArray codes = new JSONArray();
							codes.add(one[i]);
							codes.add(two[j]);
							codes.add(three[k]);
							codes.add("-");
							codes.add("-");
							bettingCodeList.add(codes);
						}
					}
				}
			} else if (lotteryPlay.startsWith("中三")) {// 中三单／复式
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							JSONArray codes = new JSONArray();
							codes.add("-");
							codes.add(one[i]);
							codes.add(two[j]);
							codes.add(three[k]);
							codes.add("-");
							bettingCodeList.add(codes);
						}
					}
				}
			} else if (lotteryPlay.startsWith("后三")) {// 后三单／复式
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							JSONArray codes = new JSONArray();
							codes.add("-");
							codes.add("-");
							codes.add(one[i]);
							codes.add(two[j]);
							codes.add(three[k]);
							bettingCodeList.add(codes);
						}
					}
				}
			} else if (lotteryPlay.startsWith("前四")) {// 前四单／复式
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				String[] four = bettingCodeArray[3].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							for (int l = 0; l < four.length; l++) {
								JSONArray codes = new JSONArray();
								codes.add(one[i]);
								codes.add(two[j]);
								codes.add(three[k]);
								codes.add(four[l]);
								codes.add("-");
								bettingCodeList.add(codes);
							}
						}
					}
				}
			} else if (lotteryPlay.startsWith("后四")) {// 后四单／复式
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				String[] four = bettingCodeArray[3].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							for (int l = 0; l < four.length; l++) {
								JSONArray codes = new JSONArray();
								codes.add("-");
								codes.add(one[i]);
								codes.add(two[j]);
								codes.add(three[k]);
								codes.add(four[l]);
								bettingCodeList.add(codes);
							}
						}
					}
				}
			} else if (lotteryPlay.startsWith("五星")) {
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				String[] four = bettingCodeArray[3].split(" ");
				String[] five = bettingCodeArray[4].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							for (int l = 0; l < four.length; l++) {
								for (int m = 0; m < five.length; m++) {
									JSONArray codes = new JSONArray();
									codes.add(one[i]);
									codes.add(two[j]);
									codes.add(three[k]);
									codes.add(four[l]);
									codes.add(five[m]);
									bettingCodeList.add(codes);
								}
							}
						}
					}
				}
			} else if (lotteryPlay.startsWith("前二")) {
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						JSONArray codes = new JSONArray();
						codes.add(one[i]);
						codes.add(two[j]);
						codes.add("-");
						codes.add("-");
						codes.add("-");
						bettingCodeList.add(codes);
					}
				}
			} else if (lotteryPlay.startsWith("后二")) {
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						JSONArray codes = new JSONArray();
						codes.add("-");
						codes.add("-");
						codes.add("-");
						codes.add(one[i]);
						codes.add(two[j]);
						bettingCodeList.add(codes);
					}
				}
			} else if (lotteryPlay.startsWith("任")) {
				String[] bettingCodeArray = bettingCode.split(",");
				String[] one = bettingCodeArray[0].split(" ");
				String[] two = bettingCodeArray[1].split(" ");
				String[] three = bettingCodeArray[2].split(" ");
				String[] four = bettingCodeArray[3].split(" ");
				String[] five = bettingCodeArray[4].split(" ");
				for (int i = 0; i < one.length; i++) {
					for (int j = 0; j < two.length; j++) {
						for (int k = 0; k < three.length; k++) {
							for (int l = 0; l < four.length; l++) {
								for (int m = 0; m < five.length; m++) {
									JSONArray codes = new JSONArray();
									codes.add(one[i]);
									codes.add(two[j]);
									codes.add(three[k]);
									codes.add(four[l]);
									codes.add(five[m]);
									bettingCodeList.add(codes);
								}
							}
						}
					}
				}
			}
		}
		bettingInfo.setLotteryBettingCodeList(bettingCodeList.toString());// 设置投注号码组集
		bettingInfo.setLotteryBettingNumber(bettingCodeList.size());// 设置数量
		String bettingMode = bettingInfo.getLotteryBettingMode();// 投注单位
		double baseAmount = 2.0d;// 查询当前玩法价格基础值
		double basePrice = 100.0d;//查询当前玩法基础奖金
		double scale = 1.2d;// 当前代理玩法比例
		double totalAmount = baseAmount * bettingCodeList.size();//消费金额＝ 单价 ＊ 数量
		double totalPrice = basePrice * bettingCodeList.size() * scale;//总奖金 ＝ 玩法奖金 ＊ 号码数 ＊ 代理人奖金比例
		bettingInfo.setLotteryBettingPrize(totalPrice);//设置奖金
		if ("2".equals(bettingMode)) {
			totalAmount = totalAmount * 0.1;
		} else if ("3".equals(bettingMode)) {
			totalAmount = totalAmount * 0.01;
		}
		bettingInfo.setLotteryBettingAmount(totalAmount);//设置消费金额
		return totalAmount;
	}
}
